# KnifeProjectile.gd
class_name KnifeProjectile
extends Area2D # Use Area2D for detecting hits

@export var speed: float = 400.0
@export var lifetime: float = 2.0 # Seconds before disappearing

var current_damage: float = 1.0
var direction: Vector2 = Vector2.RIGHT
var current_pierce: int = 0
var current_bounce: int = 0

var hit_enemies: Array[Node] = [] # Track hit enemies to prevent multi-hits/loops

@onready var sprite: Sprite2D = $Sprite2D
@onready var collision_shape: CollisionShape2D = $CollisionShape2D
@onready var lifetime_timer: Timer = $LifetimeTimer

# Collision: Layer 4 (player_weapon), Mask 8 (enemy_hurtbox)

func _ready():
	# Connect area_entered signal in editor or here
	area_entered.connect(_on_area_entered)
	lifetime_timer.wait_time = lifetime
	lifetime_timer.one_shot = true
	lifetime_timer.timeout.connect(queue_free) # Destroy after time
	lifetime_timer.start()


func initialize(dmg: float, dir: Vector2, pierce: int, bounce: int):
	current_damage = dmg
	direction = dir.normalized()
	current_pierce = pierce
	current_bounce = bounce
	# Set initial rotation based on direction if sprite is oriented rightwards
	rotation = direction.angle()


func _physics_process(delta):
	if GameManager.is_paused or GameManager.is_game_over: return
	# Move the projectile
	global_position += direction * speed * delta


# Required by enemy hurtbox check
func get_damage() -> float:
	return current_damage


func _on_area_entered(area):
	# Check if the entered area is an enemy hurtbox
	if area.is_in_group("enemy_hurtbox") and not GameManager.is_game_over:
		var enemy = area.get_owner() # Assuming Hurtbox Area2D is child of the enemy CharacterBody2D
		if is_instance_valid(enemy) and enemy.has_method("take_damage") and not hit_enemies.has(enemy):
			hit_enemies.append(enemy) # Track hit enemy
			print("Knife projectile hit:", enemy.name)
			# Enemy take_damage logic is handled by the enemy's hurtbox signal connection

			# Handle Pierce
			if current_pierce > 0:
				current_pierce -= 1
				print("Pierced! Remaining:", current_pierce)
				# Continue moving
			# Handle Bounce (if not piercing)
			elif current_bounce > 0:
				current_bounce -= 1
				print("Bouncing! Remaining:", current_bounce)
				var next_target = find_nearest_unhit_enemy(enemy.global_position, 200.0) # Bounce range
				if next_target:
					direction = global_position.direction_to(next_target.global_position)
					rotation = direction.angle()
					# Reset lifetime? Optional.
					# lifetime_timer.start()
				else:
					queue_free() # No bounce target found
			# No pierce or bounce left
			else:
				queue_free() # Destroy projectile on hit


# Called by BaseEnemy's _on_hurtbox_area_entered via area.on_hit_enemy(self)
# This function isn't strictly needed if pierce/bounce is handled in _on_area_entered
# func on_hit_enemy(enemy):
#    if hit_enemies.has(enemy): return # Already processed this hit
#    hit_enemies.append(enemy)
#    # ... Pierce/Bounce logic identical to _on_area_entered ...


func find_nearest_unhit_enemy(from_position: Vector2, search_range: float) -> Node2D:
	var nearest_enemy: Node2D = null
	var min_dist_sq = search_range * search_range

	var enemies = get_tree().get_nodes_in_group("enemies")
	for enemy in enemies:
		# Check if valid, alive, not already hit by this projectile
		if is_instance_valid(enemy) and enemy.has_method("is_dying") and not enemy.is_dying and not hit_enemies.has(enemy):
			var dist_sq = from_position.distance_squared_to(enemy.global_position)
			if dist_sq < min_dist_sq:
				min_dist_sq = dist_sq
				nearest_enemy = enemy
	return nearest_enemy